﻿using DeviceFaultPushService.MessagePushService.Models;
using DeviceFaultPushService.SystemService;
using System.IO.Ports;
using System.Text;
using System.Text.Json;

namespace DeviceFaultPushService.MessagePushService.Communication;

public class SerialPortCommunication : ICommunication
{
    private object _lock = new();

    private SerialPort fSerialPort;

    public bool IsConnected { get { return fSerialPort.IsOpen; } }

    public void SendSms(string phone, string message, out string results)
    {
        lock (_lock)
        {
            if (fSerialPort.IsOpen)
            {
                string strContent = phone + ":0:" + message;
                fSerialPort.Write(strContent);
            }

            results = "";
        }
    }

    public void SendCall(string phone, string message, out string results)
    {
        lock (_lock)
        {
            if (fSerialPort.IsOpen)
            {
                string strContent = phone + ":3:" + message;
                fSerialPort.Write(strContent);

            }
            results = "";
        }
    }

    public bool Connect()
    {
        try
        {
            SerialCommunicationModel serialCommunication = JsonSerializer.Deserialize<SerialCommunicationModel>(GetConfiguration.Configuration.PassagewayMessage);
            if (!fSerialPort.IsOpen)
            {
                //设置波特率
                fSerialPort.BaudRate = serialCommunication.BaudRate;
                //设置COM端口
                fSerialPort.PortName = serialCommunication.SerialPort;
                fSerialPort.Encoding = Encoding.GetEncoding("GBK");
                //串行端口开启  
                fSerialPort.Open();
            }
            return true;
        }
        catch
        {
            return false;
        }
    }

    public void Disconnect()
    {
        try
        {
            if (fSerialPort.IsOpen)
            {
                fSerialPort.Close();
            }
        }
        catch (Exception)
        {
            // ignored
        }
    }
}